package com.community.task;

import com.community.system.domain.CommunityMessage;
import com.community.system.domain.request.CommunityMessageRequest;
import com.community.system.service.ICommunityMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 社区消息失效清理任务
 */
@Slf4j
@Component
public class CommunityMessageExpireTask {

    @Autowired
    private ICommunityMessageService communityMessageService;

    /**
     * 一分钟执行一次标记超过保留天数的数据为已删除
     * @Author zhanghong
     * @Date 2024/6/15 20:40
     **/
    @Scheduled(fixedDelay = 60000)
    public void communityMessageExpire(){
        List<CommunityMessage> communityMessages = communityMessageService.selectCommunityMessageList(new CommunityMessageRequest());
        // 过滤超过失效时间的
        List<Long> deleteIds = communityMessages.stream().filter(x -> {
                    Date createTime = x.getCreateTime();
                    long dayMillisecond = 24 * 60 * 60 * 1000L;
                    // 筛选发帖时间距离当前时间已超过配置的保留天数
                    return System.currentTimeMillis() - createTime.getTime() > x.getRetentionDays() * dayMillisecond;
                })
                .map(CommunityMessage::getMessageId)
                .collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(deleteIds)){
            Long[] ids = new Long[deleteIds.size()];
            deleteIds.toArray(ids);
            communityMessageService.deleteCommunityMessageByMessageIds(ids);
            log.info("定时清理过期帖子消息:" + deleteIds);
        }
    }

}
